﻿using DimensionsHelper.Common.Contracts.TableFormatter;

namespace DimensionsHelper.Client.WinUi.ViewModels;

public partial class TableFormatterInputFileViewModel : FileViewModel
{
    public TableFormatterInputFileViewModel()
    {
        SubFiles = [];
        Filter = FileFilters.Excel;
    }


    public ObservableCollection<TableFormatterSubFileViewModel> SubFiles
    {
        get;
    }


    private bool SubFileExists(string fileName) => FileExists(SubFiles, fileName);


    [RelayCommand]
    private async Task SelectInsertFile()
    {
        IReadOnlyList<string> files = await App.GetService<IFilePikerService>()
            .PickMultipleFilesAsync(FileFilters.Csv);

        foreach (string file in files)
        {
            if (string.IsNullOrEmpty(file) || SubFileExists(file))
            {
                continue;
            }

            TableFormatterSubFileViewModel viewModel = new()
            {
                ExistPredicate = SubFileExists,
                RemoveCallback = vm =>
                {
                    if (vm is TableFormatterSubFileViewModel sub)
                    {
                        SubFiles.Remove(sub);
                    }
                },
                Filter = FileFilters.Csv,
                FileName = file
            };

            SubFiles.Add(viewModel);
        }
    }


    public TableInputFileInfo? GetFileInfo()
    {
        if (string.IsNullOrEmpty(FileName))
        {
            return null;
        }

        List<TableInsertFileInfo> insertFiles = [];
        List<TableReplaceFileInfo> replaceFiles = [];

        foreach (TableFormatterSubFileViewModel subFile in SubFiles)
        {
            if (subFile.IsInsertFile)
            {
                TableInsertFileInfo insertInfo = subFile.GetInsertFileInfo();
                if (TableInsertFileInfo.IsValid(insertInfo))
                {
                    insertFiles.Add(insertInfo);
                }
            }
            else
            {
                TableReplaceFileInfo replaceInfo = subFile.GetReplaceFileInfo();
                if (TableReplaceFileInfo.IsValid(replaceInfo))
                {
                    replaceFiles.Add(replaceInfo);
                }
            }
        }

        return new TableInputFileInfo(FileName, insertFiles, replaceFiles);
    }
}